package com.njwt.cloud.msconsumer.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.njwt.cloud.mscommon.pojo.OrderModel;

import com.njwt.cloud.msconsumer.service.VipServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

/**
 * @author <a href="mailto:xingxiao@gtmap.cn">xingxiaofeng</a>
 * @version2.1 2022-04-24
 * @description
 */
@RestController
public class OrderHystrixController {
    @Autowired
    private RestTemplate restTemplate;

     @Autowired
     private VipServiceImpl vipService;
    @GetMapping("/vipo/{id}")
    public OrderModel loadVipOrders(@PathVariable Integer id) {
        OrderModel result=null;
        try {
            //模拟短时间内的并发及请求，会将请求进行合并，
//传入的参数被封装到List集合
            Future<OrderModel> future1 = vipService.loaddFutureOrders(5);
            Future<OrderModel> future2 = vipService.loaddFutureOrders(6);
            Future<OrderModel> future3 = vipService.loaddFutureOrders(7);
            Future<OrderModel> future4 = vipService.loaddFutureOrders(8);
            //通过future1对象，获得响应回来的订单对象
            result=future1.get();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    /***
     * 服务熔断
     * 处理查询某个订单详细信息的请求
     */
    @GetMapping("/loadOrders/{id}")
    public OrderModel loadOrders(@PathVariable Integer id) {
        return vipService.loadOrdersService(id);
    }

    /**
     * 线程隔离
     * @param id
     * @return
     */
    @GetMapping("/loadThreadOrders/{id}")
    public OrderModel loadThreadOrders(@PathVariable Integer id) {
        return vipService.loadOrdersThreadService(id);
    }

    /**
     * 信号隔离
     * @param id
     * @return
     */
    @GetMapping("/loadSignalOrders/{id}")
    public OrderModel loadSignalOrders  (@PathVariable Integer id) {
        return  vipService.loadOrdersSignalService(id);
    }

    /**
     * 服务降级
     * @param id
     * @return
     */
    @HystrixCommand(defaultFallback="fallBack01")
    @GetMapping("/loadOrder")
    public OrderModel loadVipOrdersService(Integer id) {
        //通过制定需要调用的远程服务的名字获得服务实例对象
        String url="http://orders-provider/order/orders/"+id;
        System.out.println("url========="+url);
        //调用远程的服务
        OrderModel orders = restTemplate.getForObject(url.toString(), OrderModel.class);
        return orders;
    }
    /***
     * 定义fellback方法，返回托底数据
     */
    private OrderModel fallBack01() {

        OrderModel orders = new OrderModel();
        orders.setId(-1111);
        orders.setRemark("系统繁忙稍后再试......");
        return orders;
    }

}
